package com.czxy.controller;

import com.czxy.domain.BaseDict;
import com.czxy.domain.Customer;
import com.czxy.service.BaseDictService;
import com.czxy.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/customer")
public class CustomerController {


    @Resource
    private CustomerService customerService;
    @Resource
    private BaseDictService baseDictService;

    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<Customer> list = customerService.findAll();
        model.addAttribute("list", list);
        return "customer/list";
    }


    @RequestMapping("/addUI")
    public String addUI(Model model) {
        // 分别调用Service获取两个下拉菜单的内容 转存到指定的jsp 进行展示
        List<BaseDict> allCustSource = baseDictService.findAllCustSource();
        List<BaseDict> allCustLevel = baseDictService.findAllCustLevel();

        model.addAttribute("allCustSource", allCustSource);
        model.addAttribute("allCustLevel", allCustLevel);
        return "customer/add";
    }

    @RequestMapping("/add")
    public String add(Customer customer){
        customerService.insert(customer);
        return "redirect:/customer/findAll.action";
    }

    @RequestMapping("/delete")
    public String delete(Customer customer){
        customerService.delete(customer);
        return "redirect:/customer/findAll.action";
    }

    @RequestMapping("/editUI")
    public String editUI(Customer customer,Model model){

        // 根据id 获取Customer数据
        Customer custById = customerService.findById(customer);
        // 把两个下拉菜单数据查询到
        List<BaseDict> allCustSource = baseDictService.findAllCustSource();
        List<BaseDict> allCustLevel = baseDictService.findAllCustLevel();


        //把三个数据转给前端
        model.addAttribute("allCustSource", allCustSource);
        model.addAttribute("allCustLevel", allCustLevel);
        model.addAttribute("customer", custById);

        return "customer/edit";

    }

    @RequestMapping("/edit")
    public String edit(Customer customer,Model model){
        //调用Service获取结果
        boolean rel = customerService.update(customer);

        // 根据结果给出响应
        if(rel){
            // 修改成功
            return "redirect:/customer/findAll.action";
        }else{
            //修改失败
            // 下拉菜单数据
            List<BaseDict> allCustSource = baseDictService.findAllCustSource();
            List<BaseDict> allCustLevel = baseDictService.findAllCustLevel();
            model.addAttribute("allCustSource", allCustSource);
            model.addAttribute("allCustLevel", allCustLevel);
            //从前端接收到的 客户信息
            model.addAttribute("customer", customer);
            // 失败信息
            model.addAttribute("editMsg", "修改失败,客户名跟别的客户重名了");

            return "customer/edit";
        }
    }
}